package com.gec.system.service.impl;

import com.gec.system.custom.CustomUser;
import com.gec.system.exception.MyCustomException;
import com.gec.system.service.SysMenuService;
import com.gec.system.service.SysUserService;
import com.gec.system.system.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl  implements UserDetailsService {

//    public UserDetailsServiceImpl(SysUserService userService, SysMenuService menuService) {
//        this.userService = userService;
//        this.menuService = menuService;
//    }
    @Autowired
    private  SysUserService userService;
    @Autowired
    private SysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getUserInfoUserName(username);
        if (sysUser==null){
            throw new MyCustomException(20001,"用户不存在");
        }
        if (sysUser.getStatus()==0){
            throw new MyCustomException(20003,"账号被停用..");
        }

//        return new CustomUser(sysUser, Collections.emptyList());
        List<String> permsList = menuService.findUserPermsList(sysUser.getId());
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perms : permsList) {
            authorities.add(new SimpleGrantedAuthority(perms));
            System.out.println("perms = " + perms);
        }

        return new CustomUser(sysUser,authorities);
    }

}
